package net.xdclass.service.impl;

import net.xdclass.component.MailService;
import net.xdclass.constant.CacheKey;
import net.xdclass.enums.BizCodeEnum;
import net.xdclass.enums.SendCodeType;
import net.xdclass.request.UserRegisterRequest;
import net.xdclass.service.NotifyService;
import net.xdclass.util.CheckUtil;
import net.xdclass.util.CommonUtil;
import net.xdclass.util.JsonData;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class NotifyServiceImpl implements NotifyService {
    @Autowired
    private MailService mailService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private static final String SUBJECT = "邮箱验证码";
    private static final String CONTENT = "你的邮箱验证码是:%s,打死也不要告诉别人";
    @Override
    public JsonData sendCode(SendCodeType sendCodeType, String to) {
        String key = String.format(CacheKey.CHECK_CODE_KEY, sendCodeType.name(), to);
        String value = stringRedisTemplate.opsForValue().get(key);
        if (StringUtils.isNoneBlank(value)){
            long cacheTime = Long.parseLong(value.split("_")[1]);
            if(CommonUtil.getCurrentTimeStamp()-cacheTime<60*1000){
                return JsonData.buildResult(BizCodeEnum.CODE_LIMITED);
            }
        }
        String code = CommonUtil.getRandomCode(6);
        String codeValue = code + "_" + CommonUtil.getCurrentTimeStamp();
        stringRedisTemplate.opsForValue().set(key,codeValue,60*1000*10, TimeUnit.MILLISECONDS);
        if (CheckUtil.isEmail(to)) {
            mailService.sendMail(to, SUBJECT, String.format(CONTENT,code));
            return JsonData.buildSuccess("发送成功");
        } else{
            //TODO 短信
        }
        return JsonData.buildResult(BizCodeEnum.CODE_TO_ERROR);
    }

    @Override
    public boolean checkCode(String code, SendCodeType sendCodeType, String to) {
        String cacheKey = String.format(CacheKey.CHECK_CODE_KEY, sendCodeType.name(), to);
        String cacheValue = stringRedisTemplate.opsForValue().get(cacheKey);
        if (StringUtils.isNoneBlank(cacheValue)){
            String s = cacheValue.split("_")[0];
            if (s.equals(code)){
                return true;
            }
        }
        return false;
    }

}
